package com.forum.service.impl;

import com.forum.common.exception.BusinessException;
import com.forum.dto.LoginDTO;
import com.forum.dto.UserDTO;
import com.forum.mapper.UserMapper;
import com.forum.service.RoleService;
import com.forum.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ObjectMapper objectMapper;
    
    @Autowired
    private RoleService roleService;

    @Override
    public UserDTO getUserById(Long id) {
        UserDTO userDTO = userMapper.selectById(id);
        if (userDTO == null) {
            throw new BusinessException("用户不存在");
        }
        return userDTO;
    }

    @Override
    @Transactional
    public void register(UserDTO userDTO) {
        // 检查用户名是否已存在
        if (!checkUsernameAvailable(userDTO.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        // 加密密码
        userDTO.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        userDTO.setState(1); // 默认启用

        int result = userMapper.insert(userDTO);
        if (result != 1) {
            throw new BusinessException("注册失败");
        }
    }

    @Override
    public UserDTO login(LoginDTO loginDTO) {
        UserDTO userDTO = userMapper.selectUserByUsername(loginDTO.getUsername());
        if (userDTO == null || !passwordEncoder.matches(loginDTO.getPassword(), userDTO.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }
        if (userDTO.getState() == 0) {
            throw new BusinessException("账号已被禁用");
        }
        
        // 清除密码等敏感信息
        userDTO.setPassword(null);
        return userDTO;
    }

    @Override
    @Transactional
    public void updateUser(UserDTO userDTO) {
        // 检查用户是否存在
        UserDTO existingUser = userMapper.selectById(userDTO.getId());
        if (existingUser == null) {
            throw new BusinessException("用户不存在");
        }

        // 如果要更新用户名，检查新用户名是否已存在
        if (userDTO.getUsername() != null && !userDTO.getUsername().equals(existingUser.getUsername())) {
            if (!checkUsernameAvailable(userDTO.getUsername())) {
                throw new BusinessException("用户名已存在");
            }
        }

        // 验证title字段的JSON格式
        if (userDTO.getTitle() != null) {
            try {
                // 尝试解析JSON，确保它是有效的JSON数组格式
                Object parsed = objectMapper.readValue(userDTO.getTitle(), Object.class);
                if (!(parsed instanceof java.util.List)) {
                    throw new BusinessException("标签必须是数组格式");
                }
            } catch (Exception e) {
                throw new BusinessException("标签格式不正确: " + e.getMessage());
            }
        }

        int result = userMapper.updateById(userDTO);
        if (result != 1) {
            throw new BusinessException("更新用户信息失败");
        }
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        UserDTO userDTO = userMapper.selectById(id);
        if (userDTO == null) {
            throw new BusinessException("用户不存在");
        }
        int result = userMapper.deleteById(id);
        if (result != 1) {
            throw new BusinessException("删除用户失败");
        }
    }

    @Override
    public boolean checkUsernameAvailable(String username) {
        return userMapper.selectUserByUsername(username) == null;
    }
    
    @Override
    public Long validateCredentials(String username, String password) {
        UserDTO user = userMapper.selectUserByUsername(username);
        if (user == null) {
            return null;
        }
        
        // 验证密码
        if (passwordEncoder.matches(password, user.getPassword())) {
            return user.getId();
        }
        
        return null;
    }
    
    @Override
    public Long getUserIdByUsername(String username) {
        UserDTO user = userMapper.selectUserByUsername(username);
        return user != null ? user.getId() : null;
    }
    
    @Override
    public UserDTO getUserDetailsWithRoles(Long userId) {
        // 获取基本用户信息
        UserDTO userDTO = getUserById(userId);
        if (userDTO == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 清除敏感信息
        userDTO.setPassword(null);
        
        // 获取用户角色列表
        List<String> roleCodes = roleService.getRoleCodesByUserId(userId);
        userDTO.setRoles(roleCodes);
        
        // 设置主要角色（优先级：超级管理员 > 管理员 > 普通用户 > 游客）
        if (roleCodes.contains("ROLE_SUPER_ADMIN")) {
            userDTO.setRole("ROLE_SUPER_ADMIN");
        } else if (roleCodes.contains("ROLE_ADMIN")) {
            userDTO.setRole("ROLE_ADMIN");
        } else if (roleCodes.contains("ROLE_USER")) {
            userDTO.setRole("ROLE_USER");
        } else if (roleCodes.contains("ROLE_GUEST")) {
            userDTO.setRole("ROLE_GUEST");
        } else {
            userDTO.setRole("ROLE_USER"); // 默认为普通用户
        }
        
        return userDTO;
    }
}

